<template>
  <view class="fillingAll" :style="{ opacity: curPage === 'map' ? '0' : '1', height: '100vh' }" ref="filling">
    <uni-nav-bar title="加注" color="#333" :border="false" statusBar></uni-nav-bar>
    <!-- 地图 -->
    <mapFing :latitude="latitude" :longitude="longitude" ref="MapPage" @fillDs="() => (fillD = true)"
      @locationNew="locationNew" @curens="curens"></mapFing>
    <!-- 搜索框 -->
    <searchTop @locations="locations" v-if="curPage !== 'map'" :locationName="locationName"></searchTop>
    <!-- 加注图标 -->
    <ScanCodeIcon v-if="curPage !== 'map'" :orderJID="FillingOrder"></ScanCodeIcon>
    <!-- 底部操作 -->
    <view class="filButtom" v-if="curPage !== 'map'" style="bottom: 6vh;">
      <view class="icon" @click="changType" v-if="fillListAll">
        <uni-icons type="top" color="#666" size="36" v-if="!fillD"></uni-icons>
        <uni-icons type="bottom" color="#666" size="36" v-else></uni-icons>
      </view>
      <!-- 加注列表 -->
      <view class="filList" @touchstart="start" @touchend="end" v-if="!fillD" style="height: 60vh;">
        <view class="filLista" v-if="fillListAll.length > 0">
          <FillingList :fillListAll="fillListAll" :slide="slide" @tabChange="tabChange"></FillingList>
        </view>
        <view v-else class="filList_k">
          <image :src="fillder1"></image>
          <text>暂无加注机</text>
        </view>
      </view>
      <!-- 3d列表轮播 -->
      <Filling v-if="fillD" :list="fillListAll" :effect3d="true" :height="180" mode="none" :autoplay="false"
        :current="current" @change="changeActive($event)" @tabChange="tabChange" ref="Dfilling"></Filling>
    </view>
    <!-- 底部功能按钮 -->
    <bottomFil :active="0"></bottomFil>
    <!-- 选择地址列表 -->
    <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
    <!-- 微信分享 -->
    <webWechat></webWechat>
    <!-- 当前位置经纬度 -->
    <Lotlats @position="position" ref="Lotlat"></Lotlats>
    <!-- 账户充值到账 -->
    <ReceivedPop></ReceivedPop>
  </view>
</template>

<script setup lang="ts">
  import { showLoading } from '@/utils/prompt';
  import { fillingLists, orderJ } from '@/gql/filling';
  import bottomFil from '@c/pobulic/bottomFil.vue';
  import { getDriverID } from '@/stores/driverID';
  import FillingList from '@c/mapFilling/fillingList.vue';
  import mapFing from '@c/mapFilling/map.vue';
  import ScanCodeIcon from '@c/mapFilling/scanCodeIcon.vue';
  import searchTop from '@c/mapFilling/search.vue';
  import ReceivedPop from '@c/pobulic/Received.vue';
  import Filling from '@c/mapFilling/swiper.vue';
  import { fillder1 } from '@/utils/Static';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import Lotlats from '@c/team/Lotlat.vue';
  import webWechat from '@c/pobulic/webWechat.vue';
  import { toPublish } from '@mqtt';
  import type { Ref } from 'vue';
  import { ref } from 'vue';
  import { defaultFail, getLocation } from '@/utils/wechat.jssdk';
  /**
   * 地图加注页面
   * @param driver_id 用户ID
   * @param fillListAll 加注机列表
   * @param startData  页面上下滑动值
   * @param longitude  纬度
   * @param latitude  经度
   * @param slide  是否向上滑动
   * @param thumbnail  缩略图
   * @param MapPage  地图状态定义值
   * @param Dfilling  3D轮播图定义值
   * @param current  3D轮播图当前的索引值
   * @param FillingOrder  正在加注订单的ID
   * @param Lotlat  获取经纬度组件的定义值
   * @param pageHeight  当前可视化页面的高度
   * @param curPage  选择地图列表及当前页面的状态切换
   * @return
   */
  // uni.setStorageSync('storage_key',{id:1})
  // uni.setStorageSync('driver_ID',1)
  const driver_id = getDriverID();
  const fillListAll : Ref<any[]> = ref([]);
  const startData = ref({ clientY: 0 });
  const longitude = ref(0); //纬度113.62493
  const latitude = ref(0); //经度34.74725
  const slide = ref(true); //是否向上滑动
  const fillD = ref(true); //是否出现3D轮播
  const thumbnail = ref(false); //缩略图
  const MapPage = ref(null);
  const Dfilling = ref(null);
  const current = ref(); //初始化第几向
  const FillingOrder = ref(0);
  const Lotlat = ref(null)

  const pageHeight = ref('')

  const mapURI = ref('');
  const locationName = ref('')
  // data
  const curPage : Ref<'form' | 'map'> = ref('form');
  onShow(() => {
    const locations = uni.getStorageSync('location');
    if (locations) {
      //选择特定位置查看地图信息
      Especially(locations);
      MapPage.value.moves = true;
      MapPage.value.first = true;
      return;
    } else {
      locationName.value = '请输入地址'
    }
    //存储时间戳并计算获取当前地理位置信息
    DataStamp();
    setTimeout(() => {
      MapPage.value.moves = false;
    }, 150);
    orderFilling();
    uni.removeStorageSync('fillingID');
  });
  onLoad(() => {
    uni.getSystemInfo({
      success: function (res) {
        pageHeight.value = res.windowHeight.toString();
      },
    })
  });
  /**
   * 计算获取经纬度的时间 避免每次都会获取经纬度
   */
  function DataStamp() {
    //当前时间戳
    const Time = Date.parse(new Date().toString()) / 1000;
    //存储的时间戳
    const OldTime = Number(uni.getStorageSync('TimeStamp'));
    //时间差
    const Jtime = Number(Time) - OldTime;
    //存储的经纬度
    const information = uni.getStorageSync('positions');
    if (Jtime > 600 || !information) {
      uni.setStorageSync('TimeStamp', Time);
      //获取位置信息
      setTimeout(() => {
        Lotlat.value.locationList();
      }, 100)
    } else {
      //选择特定位置查看地图信息
      Especially(information);
    }
  }
  /**
   * 获取当前城市信息
   * @param  lat 当前位置的纬度
   * @param  lot 当前位置的经度
   * @return MapPage 修改地图页面的first状态
   */
  function position(lat : any, lot : any) {
    if (uni.getStorageSync('location')) {
      MapPage.value.first = false;
      return
    }
    longitude.value = lot;
    latitude.value = lat;
    const lots = {
      lng: longitude.value,
      lat: latitude.value,
    };
    uni.setStorageSync('positions', lots);
    //获取加注列表
    fillings();
    //获取加注机列表
    setTimeout(() => {
      MapPage.value.fillLists(longitude.value, latitude.value);
    }, 100)
  }

  /**
   * 输入框输入内容显示
   * 再次获取当前位置信息
   */
  function locationNew() {
    locationName.value = '请输入地址'
    DataStamp()
  }
  /**
   * 重新获取当前经纬度位置
   * @param {Object} lot 经纬度
   */
  function Especially(lot : any) {
    console.log(lot.lng + '*******' + lot.lat + '------------')
    longitude.value = lot.lng;
    latitude.value = lot.lat;
    fillings();
    //获取加注机列表
    MapPage.value.fillLists(longitude.value, latitude.value);
    uni.removeStorageSync('location');
  }
  /**
   * 获取加注列表
   */
  function fillings() {
    showLoading('正在加载');
    const payload = {
      query: fillingLists,
      variables: {
        longitude: Number(longitude.value),
        latitude: Number(latitude.value),
        type: '',
      },
    };
    toPublish('ql/driver/getFillingList', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      fillListAll.value = data.fill_list;
    });
  }
  /**
   * 是否存在正在家住中的订单
   */
  function orderFilling() {
    if (!driver_id) {
      return
    }
    const payload = {
      query: orderJ,
      variables: {
        driver_id,
      },
    };
    toPublish('ql/driver/doFillingOrderId', payload, (obj : any) => {
      const { data } = obj;
      FillingOrder.value = data.do_filling_order_id.order_id;
    });
  }
  /**
   * 调整加注列表显示方式
   */
  function changType() {
    fillD.value = !fillD.value;
  }
  /**
   * @param {Object} index 当前加注机索引值
   */
  function changeActive(index : number) {
    MapPage.value.changeActive(index);
  }
  /**
   * @param {Object} e 页面滑动
   */
  function start(e : any) {
    startData.value.clientY = e.changedTouches[0].clientY;
  }
  /**
   * @param {Object} e 页面滑动结束 计算上下滑动
   */
  function end(e : any) {
    const subY = e.changedTouches[0].clientY - startData.value.clientY;
    if (subY > 50) {
      if (!slide.value) {
        thumbnail.value = true;
        return;
      }
      slide.value = false;
      console.log('下滑');
    } else if (subY < -50) {
      slide.value = true;
      thumbnail.value = false;
      fillD.value = false;
      console.log('上滑');
    } else {
      console.log('无效');
    }
  }
  /**
   * 获取当前位置信息
   */
  function locations() {
    showLoading('获取地理位置');
    function success(res : any) {
      uni.hideLoading();
      latitude.value = Number.parseFloat(res.latitude);
      longitude.value = Number.parseFloat(res.longitude);
      chooseLocation();
    }
    function fail() {
      // TODO
      setTimeout(() => {
        uni.getLocation({
          type: 'gcj02',
          altitude: true,
          success(res : any) {
            uni.hideLoading();
            latitude.value = Number.parseFloat(res.latitude);
            longitude.value = Number.parseFloat(res.longitude);
            chooseLocation();
          },
        });
      }, 2000);
    }
    getLocation(success, defaultFail('getLocation', fail));
  }
  /**
   * 跳转到地址列表 选择位置信息
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        curPage.value = 'form';
        Especially(loc.latlng);
        locationName.value = loc.poiname
        MapPage.value.moves = true;
        MapPage.value.first = false;
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  /**
   * 当前轮播索引位置
   */
  function curens(num : number) {
    current.value = num;
  }
  /**
   * @param {Object} id 加注机ID
   */
  function tabChange(id : number) {
    uni.navigateTo({
      url: '/pages/addUrea/filliDetail?id=' + id + '&longitude=' + longitude.value + '&latitude=' + latitude.value,
    });
  }
</script>

<style scoped lang="less">
  @import url('../index/less/filling.less');
</style>